package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.Enumeration;
//登录
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private ObjectMapper objectMapper=new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取请求中的参数
        req.setCharacterEncoding("utf8");
        //构造响应
        resp.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null || "".equals(username) || password == null || "".equals(password)) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名和密码不能为空！");
           return;
        }
        //2.和数据库中的内容进行比较
        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        if (user == null) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户不存在请先注册！");
            return;
        }
        if (!user.getPassword().equals(password)) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名或密码错误，请重新登录");
            return;
        }
        //3.创建会话
        HttpSession httpSession=req.getSession(true);
        httpSession.setAttribute("user",user);
        //4.跳转到博客列表页
        resp.sendRedirect("blog_list.html");
    }
    //检测登录状态

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        HttpSession session=req.getSession(false);
        //检测会话是否为空
        if(session==null){
            //会话为空，没有登录
            User user=new User();
            resp.getWriter().write(objectMapper.writeValueAsString(user));
            return;
        }
        //检测user对象是否为空
        User user=(User)session.getAttribute("user");
        if(user==null){
            //对象为空，不能登录
            user=new User();
            resp.getWriter().write(objectMapper.writeValueAsString(user));
            return;
        }
        //登录状态
        user.setPassword(" ");
        resp.getWriter().write(objectMapper.writeValueAsString(user));
    }
}